package cn.kgc.tangcco.utils.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * @author 李昊哲
 * @Description
 * @create 2020/12/28 9:31
 */
public class BaseMyBatisUtil {

    // SqlSession与当前线程绑定
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

    // 实例化自身
    private static BaseMyBatisUtil baseMyBatisUtil = new BaseMyBatisUtil();

    // 声明核心配置文件路径
    private static String resource = "mybatis/mybatis-config.xml";
    // 加载核心配置文件到字符流中
    private static Reader reader;
    // 构建会话工场即获取数据源
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            reader = Resources.getResourceAsReader(resource);
            // 构建会话工场即获取数据源
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 防止外部实例化该类
    private BaseMyBatisUtil() {
        super();
    }

    /**
     * 获取SqlSession
     *
     * @return SqlSession
     */
    public SqlSession openSession() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);
        }
        // 从数据源获取连接
        return sqlSession;
    }

    /**
     * 关闭SqlSession
     */
    public void close() {
        openSession().close();
    }

    /**
     * 提交事务
     */
    public void commit() {
        openSession().commit();
    }

    /**
     * 提交事务并关闭连接
     */
    public void commitAndClose() {
        openSession().commit();
        openSession().close();
    }

    /**
     * 事务回滚
     */
    public void rollback() {
        openSession().rollback();
    }

    /**
     * 事务回滚并关闭连接
     */
    public void rollbackAndClose() {
        openSession().rollback();
        openSession().close();
    }

    /**
     * 构建BaseMyBatisUtil对象
     *
     * @return BaseMyBatisUtil对象
     */
    public static BaseMyBatisUtil build() {
        return baseMyBatisUtil;
    }

    public static void main(String[] args) {
        BaseMyBatisUtil build = BaseMyBatisUtil.build();
        System.out.println(build.openSession().getConnection());
        build.close();
    }
}
